<?php

namespace App\Console\Commands\Wanggui;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\FeishuMini\SandTableEnum;
use App\Http\Controllers\OpenShop\FeishuMini\SandTableController;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Models\Common\ConfigModel;
use App\Models\Common\MapNationalBrandShopModel;
use App\Models\Common\MapNationalIndustrialParkModel;
use App\Models\Common\MapNationalStreetModel;
use App\Models\Common\MapNationalUniversitiesModel;
use App\Models\Common\MapTownshipPlanAreaModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\Wanggui\BusinessAoiModel;
use App\Models\Wanggui\SandTablePolymerizeDotInfoModel;
use App\Service\OpenShop\FeishuMini\SandTableService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use League\Geotools\Coordinate\Coordinate;
use League\Geotools\Polygon\Polygon;

class UpdateProgrammingDotByCity extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wanggui:update-programming-dot-by-city';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步各各城市下点位信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        $startTime = time();
        Log::info('WangGui-' . '开始同步各各城市下点位信息');

        //截断表
        //SandTablePolymerizeDotInfoModel::query()->truncate();

        ini_set('memory_limit', '1024M');
        //获得所有的行政区域
        $allDistrict = WangGuiCityByPower::getChinaDistrict();
        $cityInfos   = [];  //包含区的城市信息
        foreach ($allDistrict as $tempCity) {
            foreach ($tempCity['districts'] as $city) {
                $cityInfos[] = $city;
            }
        }

        $specialCityCodeJson = (string)ConfigModel::query()
            ->where('module', 'businessAoi')
            ->where('name', 'cityCodeConvert')
            ->value('value');
        $specialCityCodeArr  = json_decode($specialCityCodeJson, true);

        //循环每个区获得区内点位信息
        foreach ($cityInfos as $cityInfo) {
            // 添加商圈
            $cityCode = $cityInfo['adcode'] ?? 0;
            if (isset($cityInfo['adcode']) && in_array($cityCode, array_keys($specialCityCodeArr))) {
                $cityCode = $specialCityCodeArr[$cityCode];
            }
            $cityBusinessAoiList = BusinessAoiModel::query()
                ->where('cityCode', $cityCode)
                ->where('level', 'bizcircle')
                ->select(['id', 'boundary'])
                ->get()
                ->map(function (BusinessAoiModel $businessAoiModel) {
                    return [
                        'id'       => $businessAoiModel->id,
                        'boundary' => collect(json_decode($businessAoiModel->boundary, true))->map(function ($point) {
                            return [
                                $point['lat'],
                                $point['lng'],
                            ];
                        })->toArray()
                    ];
                })->toArray();


            $tempDot   = SandTableService::getCityDistrictDotInfo($cityInfo);
            $insertArr = [];
            foreach ($tempDot as $dots) {
                foreach ($dots as $dot) {
                    $polymerize = SandTablePolymerizeDotInfoModel::query()
                        ->firstOrNew([
                            'type'       => $dot['type'] ?? '',
                            'subType'    => $dot['key'] ?? '',
                            'relationId' => $dot['id'] ?? 0,
                        ]);

                    $polymerize->cityCode = $cityInfo['adcode'] ?? 0;
                    $polymerize->lng      = $lng = ($dot['lng'] ?? 0);
                    $polymerize->lat      = $lat = ($dot['lat'] ?? 0);
                    $polymerize->name     = $dot['name'] ?? 0;
                    $polymerize->adcode   = $dot['adcode'] ?? 0;
                    $polymerize->grade    = $dot['grade'] ?? 0;
                    $polymerize->status   = $dot['status'] ?? 0;
                    $polymerize->boundary = empty($dot['boundary']) ? '[]' : json_encode($dot['boundary'], JSON_UNESCAPED_UNICODE);

                    if (!$polymerize->businessAoiId && $lng && $lat && ($dot['type'] ?? '') == SandTableEnum::KF_MODEL_SAND_TABLE) {
                        $businessAoiId = 0;
                        foreach ($cityBusinessAoiList as $cityBusinessAoi) {
                            $polygon = new Polygon($cityBusinessAoi['boundary']);

                            // 判断点是否在区域内
                            $res = $polygon->pointInPolygon(new Coordinate([$lat, $lng]));

                            if ($res) {
                                $businessAoiId = $cityBusinessAoi['id'];
                                break;
                            }

                        }
                        $polymerize->businessAoiId = $businessAoiId;
                    }
                    $polymerize->save();

                    // $insertArr[] = [
                    //     'relationId' => $dot['id'] ?? 0,
                    //     'name'       => $dot['name'] ?? '',
                    //     'lng'        => $dot['lng'] ?? 0,
                    //     'cityCode'   => $cityInfo['adcode'] ?? 0,
                    //     'lat'        => $dot['lat'] ?? 0,
                    //     'type'       => $dot['type'] ?? '',
                    //     'subType'    => $dot['key'] ?? '',
                    //     'adcode'     => $dot['adcode'] ?? 0,
                    //     'grade'      => $dot['grade'] ?? 0,
                    //     'status'     => $dot['status'] ?? 0,
                    //     'boundary'   => empty($dot['boundary']) ? '[]' : json_encode($dot['boundary'], JSON_UNESCAPED_UNICODE),
                    // ];
                }
            }

            // $slice= array_chunk($insertArr, 1000);
            // foreach ($slice as $value) {
            //     SandTablePolymerizeDotInfoModel::query()->insert($value);
            // }

            //点位统计 3MB  --弃用
            Cache::put('openShop:sandTable:districts:programming:dot:cityCode:' . $cityInfo['adcode'], $tempDot, 87400);

            //聚合的数字统计
            $polymerize = SandTableService::getKfDotPolymerize($cityInfo['adcode']);
            Cache::put('openShop:sandTable:districts:polymerize:dot:cityCode:' . $cityInfo['adcode'], $polymerize, 87400 * 8);

            $this->info('WangGui-' . $cityInfo['name'] . '添加完成');
        }
        Log::info('WangGui-' . '同步各各城市下点位信息完成');
        dump(time() - $startTime);
    }
}
